#include "spu.h"
#include <arpa/inet.h>

//接收服务器数据
void *recv_thread(void *arg)
{
    int connfd = (long int)arg;
    char buff[1024];
    for(;;)
    {
        int recv = read(connfd, buff, sizeof(buff));
        if(recv > 0){
            printf("%s\n", buff);
            memset(buff, 0, sizeof(buff));
        }
        //如果返回是0，说明链接可能断开
        if(recv == 0){
            printf("服务器断开连接!\n");
            
        }
    }
}

int main()
{
    long int socket_fd;
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(socket_fd != -1)
        printf("套接字创建成功\n");

    struct sockaddr_in addr;
    addr.sin_port = htons(6666);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");

    if(0 == connect(socket_fd, (struct sockaddr*)&addr, sizeof(addr)))
    {
        printf("连接成功\n");
    }

    //子线程接收数据
    pthread_t tid;
    pthread_create(&tid, NULL, recv_thread, (void*)socket_fd);

    //主线线程发送数据
    char buff[100];
    for(;;)
    {
        scanf("%s", buff);
        send(socket_fd, buff, sizeof(buff), 0);
        memset(buff, 0, sizeof(buff));
    }

    return 0;
}

